<template>
  <div class="activity">
    <table-title
        title="就诊记录"
        button-text="新增记录"
        @click="addDetail">
    </table-title>

    <table-search :form="formList"></table-search>

    <el-table
        border
        stripe
        :data="tableData"
        v-loading="loading">
      <el-table-column align="center" type="index" label="序号" width="64"></el-table-column>
      <el-table-column align="center" prop="treatmentName" label="服务名称"></el-table-column>
      <el-table-column align="center" label="治疗类型">
        <template slot-scope="scope">
          {{ treatmentName[scope.row.type].name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="居民">
        <template slot-scope="scope">
          {{ userObjectData[scope.row.userId].tuserName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="服务人员">
        <template slot-scope="scope">
          {{ userObjectData[scope.row.servicePeople].tuserName }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="money" label="消费"></el-table-column>
      <el-table-column align="center" label="服务状态">
        <template slot-scope="scope">
          {{ scope.row.status == '1' ? '已完成' : '未完成' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="完成时间">
        <template slot-scope="scope">
          {{ new Date(scope.row.time).format('yyyy-MM-dd hh:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="居民评价">
        <template slot-scope="scope">
          {{
            scope.row.comment && scope.row.comment.substr(0, 52)
          }}{{ scope.row.comment && scope.row.comment.length > 52 ? '...' : '' }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.servicePeople == $store.state.userData.userId"
              type="primary"
              slot="reference"
              icon="el-icon-edit"
              size="mini"
              @click="editDetail(scope.row.treatmentId)">
          </el-button>

          <el-button
              type="danger"
              slot="reference"
              icon="el-icon-delete"
              size="mini"
              @click="deleteDetail(scope.row.treatmentId)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :page-count="totalCount"
        :current-page="currentPage"
        @current-change="changePage"
        :hide-on-single-page="true"
        class="page">
    </el-pagination>


    <!-- 图表 -->
    <el-dialog
        title="各疾病所占百分比"
        :visible="showDialog"
        :center="true"
        :append-to-body="true"
        @close="closeDialog"
        width="860px">
      <div id="data-chart" style="height: 450px; width: 750px; margin: 0 auto"></div>
    </el-dialog>
  </div>
</template>
<script>
import TableTitle from "../../../components/TableTitle";
import TableSearch from "../../../components/TableSearch";
import modelUser from "../../../models/user";
import 'zrender/lib/svg/svg';
import * as echarts from 'echarts/core';
import {LegendComponent, TitleComponent, TooltipComponent} from 'echarts/components';
import {PieChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';

echarts.use(
    [TitleComponent, TooltipComponent, LegendComponent, PieChart, CanvasRenderer]
);


export default {
  components: {TableSearch, TableTitle},
  data() {
    return {
      // 搜索表单
      formList: [
        {
          type: 'input',
          name: 'title',
          label: '服务名',
          placeholder: '请输入服务名'
        },
        {
          type: 'button',
          name: 'button1',
          isSearch: true,
          click: this.search
        }].concat(this.$store.state.userData.role != '2' ? [] : [{
        type: 'button',
        name: 'button2',
        isSearch: false,
        icon: '',
        text: '查看可视化图表',
        buttonType: 'primary',
        click: this.showChart
      }]),

      // 数据
      tableData: [
        /*{
          "comment": "string",
          "money": "string",
          "servicePeople": 0,
          "status": "string",
          "time": "2021-04-24T11:14:34.375Z",
          "treatmentId": 0,
          "treatmentName": "string",
          "type": "string",
          "userId": 0
        }*/
      ],
      userObjectData: {},
      treatmentName: {},
      treatmentType: [],

      // 分页
      loading: true,
      currentPage: 1,
      totalCount: 1,

      // 查询Body
      queryBody: this.$store.state.userData.role == '1' ? {
        servicePeople: this.$store.state.userData.userId
      } : {},

      showDialog: false
    };
  },
  created() {
    /**
     * 获取数据
     */
    this.changePage(this.currentPage);

  },
  mounted() {
  },
  methods: {
    /**
     * 发布
     */
    addDetail() {
      this.$router.push("/admin/medical-service-editor");
    },

    /**
     * 编辑
     */
    editDetail(id) {
      this.$router.push("/admin/medical-service-editor/" + id);
    },

    /**
     * 删除
     */
    deleteDetail(id) {
      this.$confirm("将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.axios.delete(this.$store.state.api + '/treatment/del?ids=' + id).then((response) => {
          if (response.data.code == 200) {
            this.$message({
              type: response.data.data ? 'success' : 'error',
              message: response.data.data ? '删除成功！' : '删除失败！'
            });
          }
          // 获取数据
          this.changePage(1);
        }).catch((error) => {
          console.log(error);
        });
      });
    },

    /**
     * 搜索
     */
    search(value) {
      if (value.title) {
        const url = this.$store.state.api + '/treatment/list?pageNum=1&pageSize=500';
        this.axios.post(url, Object.assign({treatmentName: value.title}, this.queryBody))
            .then((response) => {
              modelUser.getUserObjectData().then((userObjectData) => {
                this.userObjectData = userObjectData;
                this.tableData = response.data.data.records;
                this.totalCount = response.data.data.pages;
                this.loading = false;
              });
            })
            .catch((error) => {
              console.log(error);
            });
      }
      // 全部为空，重新加载
      else this.changePage(1);
    },

    /**
     * 获取数据
     *
     * @param val
     */
    changePage(val) {
      this.currentPage = val;
      const url = this.$store.state.api + '/treatment/list?pageNum=' + this.currentPage + '&pageSize=15';
      this.axios.post(url, this.queryBody).then((response) => {
        if (response.data.code == 200) {
          modelUser.getUserObjectData().then((userObjectData) => {
            this.userObjectData = userObjectData;
            this.getTreatmentName().then(() => {
              this.tableData = response.data.data.records;
              this.totalCount = response.data.data.pages;
              this.loading = false;
            });
          });
        }
      }).catch((error) => {
        console.log(error);
      });
    },

    /**
     * 获取疾病
     */
    getTreatmentName() {
      return new Promise((resolve) => {
        this.axios.post(this.$store.state.api + '/treatment-type/list', {})
            .then((response) => {
              if (response.data.code == 200) {
                let items = {};
                this.treatmentType = response.data.data.records;
                response.data.data.records.forEach((item) => {
                  items[item.typeId] = {
                    id: item.typeId,
                    name: item.treatmentType
                  }
                });
                this.treatmentName = items;
                resolve();
              }
            })
      })
    },


    /**
     * 显示图表
     */
    showChart() {
      this.showDialog = true;

      // 显示
      this.$nextTick(() => {
        let chartDom = document.getElementById('data-chart');
        let myChart = echarts.init(chartDom, null, {renderer: 'svg'});
        let option;


        // 所有列表ID
        // 获取每个ID的数量
        let dict = {};
        //let dictArr = [];
        this.tableData.forEach((item) => {
          if (!dict.hasOwnProperty(`${item.type}`)) dict[`${item.type}`] = 1;
          else dict[`${item.type}`] = dict[`${item.type}`] + 1;
        });


        let treatmentType = this.treatmentType.map((item) => {
          let cbk = {
            value: 0,
            name: item.treatmentType
          }
          Object.keys(dict).forEach((key) => {
            if (key == item.typeId) cbk.value = dict[key];
          });
          return cbk;
        });

        // 配置
        option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
          },
          series: [
            {
              name: '疾病',
              type: 'pie',
              radius: '50%',
              data: treatmentType,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                normal: {
                  show: true,
                  formatter: '{b}: {c}\n({d}%)'
                }
              }
            }
          ]
        };

        option && myChart.setOption(option);
      });

    },

    closeDialog() {
      this.showDialog = false;
    }
  },
};
</script>

<style lang="less" scoped>
@import "../../../assets/less/base.less";

.activity {
  color: @fontColor;
  min-height: 100%;
  background: white;
}
</style>
